#include <cmath>
#include <iostream>
#include "hHuffmanDefine.h"

namespace _hHuffmanDetail
{
	std::ostream& Node::fillOs(std::ostream& os) const
	{
		return os << _freq;
	}

	size_t Node::calcHeight() const
	{
		size_t leftH = 0, rightH = 0;

		if (_left)
			leftH = 1 + _left->calcHeight();

		if (_right)
			rightH = 1 + _right->calcHeight();

		return leftH > rightH ? leftH : rightH;
	}

	const Node* Node::getNodeByHeight(size_t height, size_t idx) const
	{
		if (!height)
		{
			if (idx)
				return NULL;
			else
				return this;
		}

		size_t nodeMax = (size_t)exp2(height);
		if (idx >= nodeMax)
			return NULL;

		size_t nodehalf = nodeMax / 2;
		if (idx < nodehalf)
		{
			if (_left)
				return _left->getNodeByHeight(height - 1, idx);

			return NULL;
		}

		if (!_right)
			return NULL;

		return _right->getNodeByHeight(height - 1, idx - nodehalf);
	}

	std::ostream& CharNode::fillOs(std::ostream& os) const
	{
		return os << _freq << _ch;
	}
}